import 'package:http/http.dart' as http;
import 'package:beautiful_soup_dart/beautiful_soup.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';
import '../models/song.dart';
import '../services/database_service.dart';

class MusicCrawlerService {
  static final MusicCrawlerService _instance = MusicCrawlerService._internal();
  factory MusicCrawlerService() => _instance;

  late final DatabaseService _databaseService;

  MusicCrawlerService._internal() {
    _databaseService = DatabaseService();
  }

  Future<void> crawlSongs() async {
    // 首先将所有歌曲设置为非热门
    await _databaseService.updateAllSongsHotStatus(false);

    // 爬取热门歌曲
    List<Song> hotSongs = await _fetchHotSongs();
    for (var song in hotSongs) {
      song.isHot = true;
      await _databaseService.upsertSong(song);
    }
    // 删除未下载且非热门的歌曲
    await _databaseService.deleteNonHotUndownloadedSongs();
  }

  Future<List<Song>> _fetchHotSongs() async {
    try {
      final response = await http
          .get(Uri.parse('https://www.kugou.com/yy/html/rank.html'), headers: {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      });

      if (response.statusCode != 200) {
        throw Exception('获取数据失败: ${response.statusCode}');
      }

      final soup = BeautifulSoup(response.body);
      final songElements = soup.findAll('.pc_temp_songlist ul li');

      List<Song> songs = [];
      for (var element in songElements) {
        try {
          final titleElement = element.find('.pc_temp_songname');
          if (titleElement != null &&
              titleElement.attributes.containsKey('title')) {
            final originalStr = titleElement.attributes['title']!.trim();
            final parts = originalStr.split(" - ");

            if (parts.length == 2) {
              final artist = parts[0].trim();
              final title = parts[1].trim();
              // 使用 MD5 生成 songId
              final songId =
                  md5.convert(utf8.encode('${artist}_${title}')).toString();

              songs.add(Song(
                songId: songId,
                title: title,
                artist: artist,
                downloadUrl: '', // 酷狗音乐需要另外的接口获取下载地址
                isDownloaded: false,
                localPath: null,
              ));
            }
          }
        } catch (e) {
          print('解析单个歌曲失败: $e');
          continue;
        }
      }

      print('成功爬取 ${songs.length} 首歌曲');
      return songs;
    } catch (e) {
      print('爬取数据失败: $e');
      return [];
    }
  }
}
